<template>
	<div class="login">
		<!-- ref属性：获取form表单的所有数据对象  获取某个控件数据对象:this.$refs.xxx-->
		<!-- model属性：表单数据对象，表单内的控件的v-model所有绑定的数据f==>data函数 -->
		<el-form ref="form" :model="form" label-width="150px">
			<el-form-item label="账号">
				<el-input v-model="form.username"></el-input>
			</el-form-item>
			<el-form-item label="密码">
				<el-input v-model="form.password" type="password"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button>取消</el-button>
				<el-button type="primary" @click="tologin()">登录</el-button>
			</el-form-item>
			<el-button @click="btn()">退出</el-button>
		</el-form>
	</div>
</template>

<script>
	import instance from '../../ajax/index.js'
	export default {
		name: 'Login',
		data() {
			return {
				form: {
					username: '',
					password: '',
					grant_type: 'password', //获取token采用密码模式
					client_id: 'sobook4', //应用id
					client_secret: '444444' //密钥
				}
			}
		},
		methods: {
			tologin() {
				//备份
				let that = this
				//将post请求的数据通过qs插件进行格式转换
				let login = this.$qs.stringify(this.form)
				//请求地址:// http://127.0.0.1:8093/oauth/token
				//application/x-www-form-urlencoded 表头
				//qs打包成json字符串
				instance.post('/oauth/token', login, {
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					}
				}).then((res) => {
					//将请求成功的token存入本地存储中
					localStorage.setItem('token', res.data.access_token)
					instance.get('/api/info/getUser').then((res) => {
						localStorage.setItem('nickname',res.data.nickname)
						localStorage.setItem('account',res.data.account)
						//role作用：1.确定登录者登陆成功之后跳转到哪个页面2.确定登录者能够访问的页面权限
						localStorage.setItem('role',res.data.role)
						
						//跳转：判断
						if(res.data.role==='G'){
							//管理员
							this.$router.push('/adm')
							return
						}else{
							this.$router.push('/hom')
							return
						}
						
						console.log(res);
					}).catch((error) => {
						console.log(error);
					})
				}).catch((error) => {
					console.log(error);
				})
				

			},
			btn(){
				localStorage.setItem('nickname','')
				localStorage.setItem('account','')
				//role作用：1.确定登录者登陆成功之后跳转到哪个页面2.确定登录者能够访问的页面权限
				localStorage.setItem('role','')
				localStorage.setItem('token', '')
			}
		}
	}
</script>

<style scoped>
	.login {
		width: 600px;
	}

	.login .el-form-item:deep(.el-form-item__label) {
		text-align: center;
	}
</style>
